<?php
/**
 * Created by PhpStorm.
 * User: Rsplwe
 * Date: 2018/6/17
 * Time: 8:49
 */

class danmaku_Query
{
    private $tmp = [];

    public function __construct(int $av, string $co)
    {
        $han_1 = json_decode($this->request("https://bilibili.zrhdwz.cn/request/api.php", false, true, [
            "type" => "danmu",
            "av" => $av
        ]), true);
        if ($han_1['status'] === "fail") {
            die($han_1['message'] . PHP_EOL);
        } else if ($han_1['status'] === "success") {
            echo "正在装载弹幕……" . PHP_EOL;
            $xml = (
            $this->request("https://comment.bilibili.com/{$han_1['url']}.xml", true)
            );
            $p = xml_parser_create();
            xml_parse_into_struct($p, $xml, $values, $index);
            xml_parser_free($p);
            $dm = [];
            $i = 1;
            foreach ($values as $k => $v) {
                if ($v['tag'] === "D") {
                    if (strpos($v['value'], $co) !== false) {
                        $p = explode(",", $v['attributes']['P']);
                        $minutes = floor($p[0] / 60);
                        $seconds = floor($p[0] % 60);
                        $dm[$i] = array(
                            "c" => $v['value'],
                            "hash" => $p[6],
                            "time" => "{$minutes}分{$seconds}秒"
                        );

                        echo "{$i}) {$dm[$i]["time"]} {$v['value']} {$p[6]}" . PHP_EOL . PHP_EOL;
                        $i++;
                    }
                }
            }
            echo "输入要查询弹幕的编号，退出输入 exit" . PHP_EOL;
            while (true) {
                fwrite(STDOUT, "");
                $cm = trim(fgets(STDIN));
                if ($cm === "exit") {
                    exit(0);
                }
                if (isset($dm[intval($cm)])) {
                    if (isset($this->tmp[$dm[intval($cm)]['hash']])) {
                        echo $this->tmp[$dm[intval($cm)]['hash']] . PHP_EOL;
                    } else {
                        $uid = json_decode(
                            $this->request("https://bilibili.zrhdwz.cn/danmu/api/hash/{$dm[intval($cm)]['hash']}")
                            , true
                        );
                        if ($uid['status'] === 0) {
                            $this->tmp[$dm[intval($cm)]['hash']] = "https://space.bilibili.com/{$uid['uid']}";
                            echo "https://space.bilibili.com/{$uid['uid']}" . PHP_EOL;
                        } else if ($uid['status'] === -1) {
                            echo $uid['msg'];
                        }
                    }
                } else {
                    echo "no found" . PHP_EOL;
                }
            }

        }
    }

    private function request(string $url, bool $decode = false, bool $post = false, $post_data = [])
    {
        $ch = curl_init();
        if ($decode) {
            curl_setopt($ch, CURLOPT_ENCODING, "chunked");
        }
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_USERAGENT, 'danmaku Query/1.0.0 (rsplwezrh@gmail.com)');
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        if ($post) {
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        }
        $result = curl_exec($ch);
        $result_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        if ($result_code === 0) {
            die("request error" . PHP_EOL);

        }
        return $result;
    }


}

fwrite(STDOUT, "输入要查询的av号，不带av前缀，例如1234567：");
$cm_av = trim(fgets(STDIN));
fwrite(STDOUT, "输入要查询的弹幕关键字：");
$cm_co = trim(fgets(STDIN));
$danmu = new danmaku_Query(intval($cm_av), $cm_co);